<template>
  <div class="editor-offic-box"
    :class="[activeName == 'writ' && !isShowArrow && 'writ-office-box', isShowArrow && 'writ-top', activeName == 'variable' && !isShowArrow && 'variable-office-box',]"
    v-resize="editorResize">
    <div class="editor-content">
      <MonitorOffice ref="office" :option="officeOption" :key="docId"></MonitorOffice>
      <div class="tool-bar-box">
        <i class="tool-icon knowledge-iconfont keowledge-xiezuo" @click="changeActive('writ')"
          v-if="isDesign == 'text'"></i>
        <i class="tool-icon knowledge-iconfont keowledge-a-huaban17" ref="tagButton" @click="changeActive('tag')"
          v-if="isDesign == 'text'"></i>
        <i class="tool-icon knowledge-iconfont keowledge-bianliang" @click="changeActive('variable')"
          v-if="isDesign == 'variable'"></i>
      </div>
      <div class="mark" v-if="tagPopover"></div>
    </div>
    <writing v-if="activeName == 'writ'" @close="handleClose" :isShowArrow="isShowArrow" :show="!showButton"
      @changeArrow="changeArrow"></writing>
    <variable v-if="activeName == 'variable'" @close="handleClose" :isShowArrow="isShowArrow" :show="!showButton"
      @changeArrow="changeArrow" :docInfo="docInfo"></variable>
    <div class="fixed-button" v-if="isShowArrow && showButton" @click="openArrow">
      <svg class="fixed-icon" :class="[activeName == 'variable' && 'bianlian']">
        <use v-bind:xlink:href="`#${activeName == 'writ' ? 'keowledge-a-zu7070' : 'keowledge-bianliang'}`"></use>
      </svg>
    </div>
    <el-popover ref="popoverRef" :virtual-ref="tagButton" trigger="click" virtual-triggering :visible="tagPopover"
      placement="bottom-start" popper-class="tag-popover-action">
      <div class="tag-body-box" v-click-outside="onClickOutside" v-loading="labelLoading">
        <div class="tag-input-box">
          <el-input v-model="searchTag" :placeholder="$t('message.placeholder.searchLabel')"></el-input>
        </div>
        <el-scrollbar ref="tagListRef">
          <div class="tag-lists">
            <div v-for="(item, index) in fileterTagList" :key="index" class="tag-item" @click="bindDocLabel(item)">
              <div class="tag-colour" :style="{ 'background-color': item.colour }"></div>
              <div></div>
              <div class="tag-name-box" v-tooltip-auto-show>
                <el-tooltip :content="item.tagName" effect="light">
                  <div class="tag-name">{{ item.tagName }}</div>
                </el-tooltip>
              </div>
              <svg class="check-icon">
                <use v-bind:xlink:href="`#${item.isSelect ? 'keowledge-a-zu3739' : 'keowledge-a-juxing2862biankuang'}`">
                </use>
              </svg>
            </div>
            <div class="more-loading-box" v-if="labelPage.current != 1 && moreLoading">
              <img class="refresh-img" src="../../assets/common/loading-page.gif">
            </div>
          </div>
        </el-scrollbar>
        <jvs-empty v-if="fileterTagList.length == 0" text="" size="160px" style="margin-top:20px;"></jvs-empty>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  nextTick,
  computed,
  getCurrentInstance,
  watch,
  onBeforeUnmount
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import MonitorOffice from '@/components/monitor-office/monitorOffice.vue'
import { getTemplateInfo } from '@/api/template'
import { getInfo, getFileUrl } from '@/api/common'
import { ClickOutside as vClickOutside } from 'element-plus'
import { isOffice } from '@/utils/util'
import { getTagAlls, editDocTag } from '@/api/tag'
import { $permissionRole } from '@/utils/role'

import useUserInfoStore from '@/store/userInfo';
import writing from '@/views/common/writing.vue'
import variable from '@/views/common/variable.vue'

import { useHookI18n } from '@/hooks/i18n'
const { $t } = useHookI18n()
const instance: any = getCurrentInstance() as ComponentInternalInstance
const proxy: any = instance.proxy as any
const userStore = useUserInfoStore()

const emit = defineEmits([""])
const props = defineProps({
  docId: {
    type: String,
    default: ''
  },
  knowId: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: ''
  },
  isDesign: {
    type: String,
    default: 'text'
  }
})

const isTemplate = ref(false)
const office = ref<InstanceType<typeof MonitorOffice>>()
const docId = ref('')
const knowId = ref('')
const officeOption = ref<any>({})
const docInfo = ref<any>({})
const isDesign = ref('')
const BASE_URL = (window.location.protocol + pluginConfig.officeCallBackUrl.substring(pluginConfig.officeCallBackUrl.indexOf('://') + 1)) || ''

const isReplace = ref(false)
const activeName = ref('')
const isShowArrow = ref(false)
const showButton = ref(false)
const editorWidth = ref(0)
const tagScrollTop = ref(0)
const tagButton = ref()
const tagListRef = ref()
const searchTag = ref('')
const tagPopover = ref(false)
const moreLoading = ref(false)
const labelLoading = ref(false)
const labelList = ref<any[]>([])
const labelPage = ref({
  size: 20,
  current: 1,
  total: 0
})

const scroll = (e: { target: { scrollTop: any; scrollHeight: any; clientHeight: any } }) => {
  const scrollTop = e.target.scrollTop
  const scrollHeight = e.target.scrollHeight
  const clientHeight = e.target.clientHeight
  if (
    scrollTop > scrollHeight - clientHeight - 10 &&
    scrollTop > tagScrollTop.value &&
    !moreLoading.value && labelPage.value.current < Math.ceil(labelPage.value.total / labelPage.value.size)
  ) {
    labelPage.value.current++
    getLabel()
  }
  tagScrollTop.value = scrollTop
}
onMounted(() => {
  // /(\${[A-Z]+}\()[.+?\)|,[0-9]+]*\)/g
  start()
})
const start = () => {
  isTemplate.value = props.type == 'template'
  docId.value = props.docId
  knowId.value = props.knowId
  isDesign.value = props.isDesign || 'text'
  if (isDesign.value == 'text') {
    tagListRef.value.wrapRef.addEventListener("scroll", scroll)
  }
  if (!isTemplate.value) {
    init()
  } else {
    getUrl()
  }
}
onBeforeUnmount(() => {
  tagListRef.value.wrapRef.removeEventListener("scroll", scroll)
})
watch(() => props.docId, () => {
  tagListRef.value.wrapRef.removeEventListener("scroll", scroll)
  start()
})
function init() {
  getInfo(docId.value).then(res => {
    if (res.data.code == 0) {
      docInfo.value = JSON.parse(JSON.stringify(res.data.data))
      getUrl()
    }
  })
}
const fileterTagList = computed(() => {
  return labelList.value.filter((item: any) => { return item.tagName.indexOf(searchTag.value) != -1 })
})
function getUrl() {
  let fun = getFileUrl
  let obj = {
    id: docInfo.value.id, isOnlyOffice: true, isTemplate: false
  }
  if (isTemplate.value) {
    fun = getTemplateInfo
    obj = {
      templateType: isDesign.value
    }
  }
  fun(isTemplate.value ? docId.value : obj, obj).then(res => {
    if (res.data.code == 0) {
      if (isTemplate.value) {
        docInfo.value = JSON.parse(JSON.stringify(res.data.data))
        if (isOffice(docInfo.value.type)) {
          nextTick(() => {
            oepnOnlyOffice(docInfo.value)
          })
        }
      } else {
        nextTick(() => {
          oepnOnlyOffice(res.data.data)
        })
      }

    }
  })
}
function oepnOnlyOffice(data: { key?: any; url?: any }) {
  officeOption.value.lang = 'zh-CN'
  if (!isTemplate.value) {
    officeOption.value.id = data.key
    officeOption.value.mode = 'edit'
    officeOption.value.isEdit = $permissionRole('document_update', docInfo.value.dcIdentifying)
    officeOption.value.url = data.url
  } else {
    officeOption.value.id = data.key
    if (!officeOption.value.id) {
      officeOption.value.id = docInfo.value.id + '-' + userStore.userInfo.id
    }
    officeOption.value.mode = isTemplate.value ? 'edit' : 'view'
    officeOption.value.isEdit = isTemplate.value === 'edit'
    officeOption.value.url = docInfo.value.fileLink
  }
  officeOption.value.comment = true
  officeOption.value.title = docInfo.value.name
  officeOption.value.fileType = docInfo.value.nameSuffix
  // officeOption.value.isEdit = true
  // 是否有编辑权限
  officeOption.value.editUrl = `${BASE_URL}/mgr/document/no/auth/only/office?id=${docInfo.value?.id}&userId=${userStore.userInfo?.id}&userName=${userStore.userInfo?.realName}&isTemple=${!!isTemplate.value}&tenantId=${userStore.userInfo?.tenantId}`
  officeOption.value.addUrl = `${BASE_URL}/mgr/document/dcLibrary/office/add`
  if (isReplace.value) {
    office.value?.reSetEditor()
  } else {
    office.value?.init()
  }
}
function editorResize({ width }) {
  editorWidth.value = width
  if (activeName.value) {
    if (activeName.value == 'variable') {
      isShowArrow.value = editorWidth.value - 1180 < 240
    } else if (activeName.value == 'writ') {
      isShowArrow.value = editorWidth.value - 1180 < 500
    }
  }
  if (!isShowArrow.value) {
    showButton.value = false
  }
}
function openArrow() {
  showButton.value = false
}
function changeArrow(val: boolean) {
  showButton.value = val
}
function changeActive(val: string) {
  showButton.value = false
  isShowArrow.value = false
  if (activeName.value == val) {
    activeName.value = ''
  } else {
    activeName.value = val
    if (activeName.value == 'variable') {
      isShowArrow.value = editorWidth.value - 1180 < 240
    } else if (activeName.value == 'writ') {
      isShowArrow.value = editorWidth.value - 1180 < 500
    } else if (activeName.value == 'tag') {
      tagPopover.value = true
      labelLoading.value = true
      getLabel()
    }
  }
}
function getLabel() {
  moreLoading.value = true
  getTagAlls({
    dcId: docInfo.value.id,
    size: labelPage.value.size,
    current: labelPage.value.current
  }).then(res => {
    if (res.data.code == 0) {
      labelPage.value.total = res.data.data.total
      labelList.value.push(...res.data.data.records)
      labelLoading.value = false
      moreLoading.value = false
    }
  })
}
function bindDocLabel(item: { isSelect: boolean }) {
  item.isSelect = !item.isSelect
  editDocTag({
    ...item,
    dcId: docInfo.value.id
  }).then(res => {
    if (res.data.code == 0) {
      let msg = "绑定标签成功"
      if (!item.isSelect) {
        msg = "解绑标签成功"
      }
      proxy.$onePrompt.$oneNotify({
        title: msg,
        type: "success",
        position: "bottom-right",
      });
    }
  })
}
function onClickOutside() {
  if (activeName.value == 'tag') {
    activeName.value = ''
    labelList.value = []
    tagPopover.value = false
    tagScrollTop.value = 0
    labelPage.value = {
      size: 20,
      current: 1,
      total: 0
    }
  }
}
function handleClose() {
  isShowArrow.value = false
  activeName.value = ''
}
</script>
<style lang="scss" scoped>
.editor-offic-box {
  width: 100%;
  height: 100%;
  position: relative;

  .editor-content {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .tool-bar-box {
    position: absolute;
    right: 140px;
    top: 0px;
    height: 28px;
    z-index: 9;
    padding: 0px 8px;
    display: flex;
    align-items: center;

    .tool-icon {
      font-size: 16px;
      width: 24px;
      height: 24px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      color: #fff;

      &:hover {
        background-color: rgba(245, 246, 247, 0.2);
      }
    }

    .tool-icon+.tool-icon {
      margin-left: 16px;
    }
  }

  .fixed-button {
    position: fixed;
    top: 80px;
    right: 0px;
    z-index: 200;
    box-shadow: 0px 1px 10px 0px rgba(54, 59, 76, 0.15);
    width: 36px;
    height: 36px;
    border-radius: 4px 0px 0px 4px;
    overflow: hidden;
    cursor: pointer;
    background-color: #f5f6f7;
    display: flex;
    align-items: center;
    justify-content: center;

    .fixed-icon {
      width: 36px;
      height: 36px;
    }

    .bianlian {
      width: 16px;
      height: 16px;
    }
  }

  .mark {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100vw;
    height: 100vh;
    z-index: 8;
  }
}

.writ-office-box {
  display: flex;

  .editor-content {
    width: 1180px;
  }

  .writing-body-fixed {
    top: 0px;
  }
}

.variable-office-box {
  display: flex;

  .editor-content {
    width: calc(100vw - 240px) !important;
  }
}

.writ-top {
  .writing-body-fixed {
    top: 0px;
  }

  ::v-deep(.variable-fixed) {
    top: 0px !important;
  }
}
</style>